import {
  Component,
  OnInit,
  Input,
  OnDestroy,
  Output,
  EventEmitter,
  ElementRef,
  ViewChild,
} from '@angular/core';
import { UtilsService } from '../../../service/utils.service';
import { UserService } from '../../../service/user.service';
import { REWARDS_MAP } from './index.map';
declare var THREE: any;
@Component({
  selector: 'app-reward',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.scss'],
})
export class RewardComponent implements OnInit {
  @ViewChild('wrapper', { static: false }) wrapper: ElementRef;
  @Input() isNotstart = true; // 是否预热
  @Output() toClose = new EventEmitter<any>();
  /* ___ _ ___ */
  public tabs: number[] = [1, 2, 3, 4, 5]; /* tabs */
  /* ___ _ ___ */
  public curTab = 1; /* 当前tab 1人气榜 2新秀榜 3女神榜 4男神榜 5神豪榜 */
  public deployUrl: string = '';
  public navIndex = 1;
  public page = 1;
  public pages = 1;
  public pageType = 1;
  public readonly rewardsMap = REWARDS_MAP;
  public mp4videoDom: any;
  public videoShow = false; /* videoShow */
  public videoDom: any; /* video dom */
  public firstPlayMp4: boolean = true; /* mp4播放器显示 */

  constructor(
    private utilsService: UtilsService,
    private userService: UserService
  ) {}

  ngOnInit() {
    this.deployUrl = this.userService.getDeployUrl();
    /* 渲染列表 */
    // console.log('=>', this.rewardsMap);
  }
  public closeClick() {
    this.toClose.emit();
  }
  /**
   * @param tab 当前tab
   * @description: 切换tab
   */
  onTabClick(tab) {
    this.resetScroll();
    this.curTab = tab;
    console.log('=>', 'cur', this.rewardsMap.get(this.curTab));
  }

  public playVideo(mp4url) {
    this.videoShow = true;
    if (this.firstPlayMp4) {
      this.initMp4Player(mp4url);
      this.firstPlayMp4 = false;
    } else {
      document.getElementById('giftMp4Box1').style.width = '';
      this.mp4videoDom = document.getElementById(
        'threeMp4video1'
      ) as HTMLVideoElement;
      this.mp4videoDom.src = mp4url;
      this.mp4videoDom.play();
      this.mp4videoDom.onended = () => {
        this.videoShow = false;
        this.mp4videoDom.innerHTML = '';
        document.getElementById('giftMp4Box1').style.width = '0px';
      };
    }
  }

  public initMp4Player(mp4url) {
    const container = document.getElementById('giftMp4Box1');
    const camera = new THREE.Camera();
    camera.position.z = 1;
    const scene = new THREE.Scene();
    this.mp4videoDom = document.getElementById('threeMp4video1');
    this.mp4videoDom.src = mp4url;
    this.mp4videoDom.play();
    this.mp4videoDom.onended = () => {
      this.videoShow = false;
      this.mp4videoDom.innerHTML = '';
      document.getElementById('giftMp4Box1').style.width = '0px';
    };

    const videoTexture = new THREE.VideoTexture(this.mp4videoDom);
    videoTexture.minFilter = THREE.LinearFilter;
    videoTexture.magFilter = THREE.LinearFilter;
    videoTexture.format = THREE.RGBAFormat;

    // shader stuff
    const uniforms = {
      time: { type: 'f', value: 1.0 },
      texture: { type: 'sampler2D', value: videoTexture },
    };
    const material = new THREE.ShaderMaterial({
      uniforms,
      vertexShader: `varying vec2 vUv;
      void main() {
        vUv = uv;
        gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
      }`,
      fragmentShader: `#ifdef GL_ES
      precision highp float;
      #endif

      uniform float time;
      uniform sampler2D texture;
      varying vec2 vUv;

      void main( void ) {
        gl_FragColor = vec4(
        texture2D(texture, vec2(0.5+vUv.x/2., vUv.y)).rgb,
        texture2D(texture, vec2(vUv.x/2., vUv.y)).r
        );
      }`,
      transparent: true,
    });
    let lastUpdate = new Date().getTime();
    const geometry = new THREE.PlaneBufferGeometry(2, 2);
    const mesh = new THREE.Mesh(geometry, material);
    mesh.scale.setScalar(0.8);
    scene.add(mesh);
    const renderer = new THREE.WebGLRenderer({ alpha: true });
    renderer.setPixelRatio(window.devicePixelRatio / 1);
    container.appendChild(renderer.domElement);
    const clientwidth = window.innerWidth || document.body.offsetWidth;
    const cliW = (clientwidth * 468) / 375;
    const cliH = (clientwidth * 833) / 375;
    renderer.setSize(cliW, cliH);

    function initRender(timeDelta) {
      uniforms.time.value += timeDelta ? timeDelta / 1000 : 0.05;
      renderer.render(scene, camera);
    }
    function initAnimate() {
      const currentTime = new Date().getTime();
      const timeSinceLastUpdate = currentTime - lastUpdate;
      lastUpdate = currentTime;
      requestAnimationFrame(initAnimate);
      initRender(timeSinceLastUpdate);
    }
    initAnimate();
  }

  resetScroll() {
    // 当前页面滚动置顶
    const wrapElement = this.wrapper.nativeElement;
    wrapElement.scrollTo({ top: 0 });
  }
}
